<template>
    <div>
        <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">活动管理</a></el-breadcrumb-item>
        <el-breadcrumb-item>活动列表</el-breadcrumb-item>
        </el-breadcrumb>

        

        <el-card class="box-card">
                <el-row>
                    <el-col :span="8">
                        <div >
                            <el-input placeholder="请输入内容"  class="input-with-select" clearable v-model="formMate.query" >
                                <el-button slot="append" icon="el-icon-search"  @click="create"></el-button>
                            </el-input>
                        </div>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
                    </el-col>
                </el-row>

                <!-- 用户列表开始 -->
                <el-table :data="users" border style="width: 100%">
                    <el-table-column type="index">

                    </el-table-column>
                    <el-table-column prop="username" label="姓名" width="180">

                    </el-table-column>
                    <el-table-column prop="email"  label="邮箱" width="180"> 

                    </el-table-column>
                    <el-table-column prop="mobile" label="电话">
                    
                    
                    </el-table-column>
                     <el-table-column prop="role_name" label="角色">
                    
                    
                    </el-table-column>
                     <el-table-column prop="mg_state" label="状态">
                         <!-- 作用域插槽,可以获取当前的数据 -->
                         <template slot-scope="scope">
                                 <el-switch
                                    v-model="scope.row.mg_state" @change="switchChange(scope.row)">
                                </el-switch>
                         </template>
                    </el-table-column>
                    <!-- 操作功能的实现 -->
                     <el-table-column  label="操作">
                            <template slot-scope="scope">
                                <!-- 修改用户的按钮 -->
                                 <el-button type="pyimary" size="mini" icon="el-icon-edit" @click="xiugai(scope.row.id)"></el-button>
                                 <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
                                 
                                      <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false"
                                                    >
                                            <!-- <el-button>上边</el-button> -->
                                            <el-button type="warning" size="mini" icon="el-icon-setting" @click="fenpei(scope.row)">
                                            </el-button>
                                      </el-tooltip>
                                 
                            </template>
                    </el-table-column>
                </el-table>
                <!-- 分页开始实现 -->

                 <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="formMate.pagenum"
                        :page-sizes="[1, 3, 5, 7]"
                        :page-size="formMate.pagesize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
        </el-card>

        <!-- 添加用户的区域 -->
        <el-dialog title="添加用户"   :visible.sync="dialogVisible"   width="30%">
                <!-- 添加用户的表单区域 -->
                <el-form :model="addForm" :rules="addrules" ref="addForm" label-width="70px">
                    <el-form-item label="用户名" prop="username" >
                        <el-input v-model="addForm.username"></el-input>
                    </el-form-item>
                     <el-form-item label="密码" prop="password">
                        <el-input v-model="addForm.password"></el-input>
                    </el-form-item>
                     <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item>
                     <el-form-item label="手机" prop="mobile">
                        <el-input v-model="addForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>


        <!-- 修改用户功能的实现 -->
        <el-dialog title="修改用户"  width="30%"  :visible.sync="xiugaiVisible" >
                    <el-form ref="xiugaiformRef" :model="xiugaiForm" label-width="80px"  :rules="rules">
                        <el-form-item label="用户名">
                            <el-input v-model="xiugaiForm.username" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="xiugaiForm.email" ></el-input>
                        </el-form-item>
                        <el-form-item label="电话" prop="mobile">
                            <el-input v-model="xiugaiForm.mobile" ></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="xiugaiVisible = false">取 消</el-button>
                        <el-button type="primary" @click="sure">确 定</el-button>
                    </span>
        </el-dialog>

        <!-- 分配角色开始 -->
            <el-dialog title="提示"   :visible.sync="fenpeiVisible" width="50%">
             <div>
                <p> 当前的用户:{{userInfo.username}}</p>
                <p>当前的角色:{{userInfo.role_name}} </p>
                <p>分配新的角色:
                      <el-select v-model="listValue" placeholder="请选择">
                            <el-option
                              v-for="item in listData"
                              :key="item.id"
                              :label="item.roleName"
                              :value="item.id">
                            </el-option>
                      </el-select>
                </p>
             </div>
              <span slot="footer" class="dialog-footer">
                <el-button @click="fenpeiVisible = false">取 消</el-button>
                <el-button type="primary" @click="queding()">确 定</el-button>
              </span>
            </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱和电话的正则校验
    var checkEmail = (rule, value, cb) => {
      // 邮箱的正则验证
      const addrule = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (addrule.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    var checkMobile = (rule, value, cb) => {
      // 手机号的正则验证
      const addrule = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (addrule.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      formMate: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      users: [],
      total: '',
      dialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addrules: {},
      addrules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            min: 10,
            max: 15,
            message: '长度在 10到 15个字符',
            trigger: 'blur'
          },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在11个字符', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
    //   定义修改用户的状态
    xiugaiVisible:false,
    xiugaiForm:{},
    rules:{},
    rules:{
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            min: 10,
            max: 15,
            message: '长度在 10到 15个字符',
            trigger: 'blur'
          },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在11个字符', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
    },
  fenpeiVisible:false,
    userInfo:{},
    listData:[],
    listValue:''
    }
  },
  created() {
    this.create()
  },
  methods: {
    async create() {
      const { data: res } = await this.$http.get('users', {
        params: this.formMate
      })
      console.log(res)
      if (res.meta.status == 200) {
        this.users = res.data.users
        this.total = res.data.total
      } else {
        console.log(res.meta.msg)
      }
    },
    // 控制分页的效果
    handleSizeChange(newSize) {
      this.formMate.pagenum = newSize
      this.create()
    },
    handleCurrentChange(newCurrent) {
      this.formMate.pagenum = newCurrent
      this.create()
    },
    // 控制状态的改变并及时向后台发送数据
    async switchChange(row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      )

      if (res.meta.status == 200) {
        console.log('更新用户状态成功了')
      } else {
        console.log('更新用户状态失败了')
        row.mg_state = !row.mg_state
      }
    },
    // 点击添加按钮添加表单的校验功能
    addUser() {
        console.log(this.$refs.addForm)
      this.$refs.addForm.validate(async valid => {
        // 如果校验失败就return
        if (!valid) return
        // 如果成功的话就发起添加用户的请求
        // console.log('ok')
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status == 201) {
          this.dialogVisible = false
          this.create()
        }
      })
    },
    // 点击按钮修改数据
    async xiugai(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if(res.meta.status==200){
           this.xiugaiForm=res.data
           console.log(this.xiugaiForm)
      }else{
          console.log(res.meta.msg)
      }
      this.xiugaiVisible=true
    },
    // 点击确定,然后更新用户成功
    sure(){
       console.log(this.$refs.xiugaiformRef)
         this.$refs.xiugaiformRef.validate(async valid => {
            if(!valid) return
            const {data:res}=await this.$http.put('users/'+this.xiugaiForm.id,{
                email:this.xiugaiForm.email,mobile:this.xiugaiForm.mobile
            })
            this.xiugaiVisible=false
            this.create()
            console.log('更新用户成功')
        })
    },
    // 删除用户操作
     async deleteUser(id){
      const result=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          console.log('已经取消了删除')          
        })
        if(result=='confirm'){
          const {data:res}=await this.$http.delete('users/'+id)
            if(res.meta.status==200){
              console.log('删除成功')
            }
        }
    },
    // 分配角色开始
   async fenpei(userInfo){
     this.userInfo=userInfo
         const {data:res}= await this.$http.get('roles')
         console.log(res)
         if(res.meta.status==200){
           this.listData=res.data
         }
        this.fenpeiVisible=true
    },
    async queding(){
      if(!this.listValue){
        return console.log('请选择要分配的角色')
      }
      const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,
           { rid : this.listValue})
           if(res.meta.status!==200){
             console.log(res)
            console.log('更新用户角色失败')
           }else{
               console.log('更新用户角色成功')
                   this.listValue=''
               this.fenpeiVisible=false
                this.create()
           }
      

    }
  }
}
</script>

<style lang='less' scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
</style>

